package modes

import (
	"errors"
	"fmt"
	"strconv"
	"time"
)

/*
 * 描述：订单管理
 *
 *	单号： 功能字符G + 20191220 + 今日支付编号0001 + 子单号00
 *
 *
 ********************************************************************************************/
type CrmOrder struct {
	Id        int64  `json:"ord_id"`                           // 订单IDxorm:"id"
	UId       int64  `json:"ord_uid" xorm:"uid"`               // 下单工号
	UName     string `json:"ord_uname" xorm:"uname"`           // 姓名
	RId       int64  `json:"ord_rid" xorm:"rid"`               // 角色ID
	TId       int64  `json:"ord_tid" xorm:"tid"`               // 小组ID
	Phone     string `json:"ord_phone" xorm:"phone"`           // 手机号
	BillNo    string `json:"ord_bill_no" xorm:"bill_no"`       // 单号
	BillType  int    `json:"ord_bill_type" xorm:"bill_type"`   // 单号类型 0 全款 1 尾款 2 定金
	SellPrice int    `json:"ord_sell_price" xorm:"sell_price"` // 出售价格
	RealPrice int    `json:"ord_real_price" xorm:"real_price"` // 实付价格
	ShowPrice int64  `json:"ord_show_price" xorm:"show_price"` // 班型价格
	RealBill  string `json:"ord_real_bill" xorm:"real_bill"`   // 支付单号
	PayType   int    `json:"ord_pay_type" xorm:"pay_type"`     // 支付方式 0 未知 1 微信 2 支付宝
	At        int64  `json:"ord_at" xorm:"at"`                 // 下单时间
	PayAt     int64  `json:"ord_pay_at" xorm:"pay_at"`         // 支付时间
	AdminId   int64  `json:"ord_admin_id" xorm:"admin_id"`     // 确认ID
	AdminName string `json:"ord_admin_name" xorm:"admin_name"` // 确认命名
	Note      string `json:"ord_note" xorm:"note"`             // 备注
	State     int    `json:"ord_state" xorm:"state"`           // 状态： 0 未支付 1 已支付 2 已退款
	Teac      int64  `json:"ord_tea_id" xorm:"teacher"`        // 班主分配：  > 0 不需要分配班主任， = 0 可以任意分配班主任 , > 0 分配给指定的班主任
	Teacher   string `json:"teacher" xorm:"-"`                 // 班主任名称

}
type JoinOrderClass struct {
	CrmOrder `xorm:"extends"`
	Cla      OrderClasses `xorm:"extends"`
}

type JoinCrmOrder struct {
	CrmOrder     `xorm:"extends"`
	OrderClasses `xorm:"extends"`
}

type JoinTeacherOrder struct {
	CrmOrder  `xorm:"extends"`
	CrmStuden `xorm:"extends"`
}

func (this *CrmOrder) TableName() string {
	return "crm_order"
}

func (this *CrmOrder) Save() (int64, error) {
	this.At = time.Now().Unix()
	return Db(2).Insert(this)
}

func (this *CrmOrder) Get() (bool, error) {
	return Db(2).Get(this)
}
func (this *CrmOrder) GetSubBillNo() (string, error) {
	var val CrmOrder
	where := fmt.Sprintf("bill_no like '%s%%'", string([]byte(this.BillNo)[:13]))
	fage, err := Db(2).Where(where).Desc("at").Get(&val)
	if err == nil {
		if !fage {
			return "", errors.New("不存在此账单")
		}
		sbu, _ := strconv.Atoi(string([]byte(val.BillNo)[13:]))
		return fmt.Sprintf("%s%.2d", string([]byte(val.BillNo)[:13]), sbu+1), nil
	}
	return "", err
}

func (this *CrmOrder) update(where string, field string) (int64, error) {
	return Db(2).Where(where).Cols(field).Update(this)
}

func (this *CrmOrder) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.update(where, field)
}

func (this *CrmOrder) count(where string) (int64, error) {
	return Db(2).Where(where).Count(this)
}

func (this *CrmOrder) Where(fage, count, page int, where, field string) ([]CrmOrder, error) {
	list := make([]CrmOrder, 0)
	var err error
	if field == "" {
		field = "id"
	}
	page--
	if 0 == fage { // 从小到大排序
		err = Db(2).Table(this.TableName()).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(2).Table(this.TableName()).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}

func (this *CrmOrder) EList(val *Pager) error {
	var field string
	list := make([]CrmOrder, 0)
	val.TName = "crm_order"
	var err error
	switch val.Coll {
	case 0:
		field = "crm_order.at" // 下单时间
	case 1:
		field = "crm_order.pay_at" // 支付时间
	case 2:
		field = "crm_order.bill_no" // 单号排序
	case 3:
		field = "crm_order.bill_type" // 支付类型
	case 4:
		field = "crm_order.real_price" // 实付价格
	case 5:
		field = "crm_order.pay_type" // 支付方式
	}
	err = Db(0).Table(val.TName).
		Desc(field).
		Where(val.ToWhere()).
		Limit(val.Count, (val.Page-1)*val.Count).
		Find(&list)
	val.Total, _ = Db(0).Table(val.TName).
		Desc(field).
		Where(val.ToWhere()).
		Count(this)
	if err == nil {
		val.List = list
	}
	return err
}

func (this *CrmOrder) List() ([]CrmOrder, error) {
	list := make([]CrmOrder, 0)
	//状态： 0 未支付 1 已支付 2 已分配
	where := ""
	if this.State == 1 {
		where = fmt.Sprintf("phone='%s' and state in(1,2) ", this.Phone)
	} else {
		where = fmt.Sprintf("phone='%s' and state =%d ", this.Phone, this.State)
	}
	err := Db(0).Table("crm_order").
		Desc("at").
		Where(where).
		Find(&list)
	return list, err
}

func GetTeacher(uid int64) string {
	var val Employee
	if uid > 0 {
		val.Id = uid
		val.Get()
		return val.Name
	}
	return "-"
}
func (this *CrmOrder) GetOrder() (bool, error) {
	where := fmt.Sprintf("id = %d and state = 0", this.Id)
	return Db(2).Where(where).Get(this)
}

func (this *CrmOrder) GetOrderInfo() (bool, error) {
	where := fmt.Sprintf("bill_no = '%s' ", this.BillNo)
	return Db(2).Where(where).Get(this)
}

func (this *CrmOrder) PList(val *Pager) error {
	var field string
	list := make([]CrmOrder, 0)
	var err error
	val.TName = "crm_order"
	switch val.Coll {
	case 0:
		field = "crm_order.at" // 下单时间
	case 1:
		field = "crm_order.pay_at" // 支付时间
	case 2:
		field = "crm_order.bill_no" // 单号排序
	case 3:
		field = "crm_order.bill_type" // 支付类型
	case 4:
		field = "crm_order.real_price" // 实付价格
	case 5:
		field = "crm_order.pay_type" // 支付方式
	}
	err = Db(2).Table(val.TName).
		//Join( "INNER", "order_classes", "crm_order.id = order_classes.order_id" ).
		Where(val.ToWhere()).
		Desc(field).
		Limit(val.Count, (val.Page-1)*val.Count).
		Find(&list)
	val.Total, _ = Db(2).Table(val.TName).
		//Join( "INNER", "order_classes", "crm_order.id = order_classes.order_id" ).
		Where(val.ToWhere()).
		Desc(field).
		Count(this)

	if err == nil {
		val.List = list
	}
	return err
}

func (this *CrmOrder) PhoneList(val *Pager) error {
	var field string
	list := make([]CrmOrder, 0)
	var err error
	val.TName = "crm_order"
	switch val.Coll {
	case 0:
		field = "crm_order.at" // 下单时间
	case 1:
		field = "crm_order.pay_at" // 支付时间
	case 2:
		field = "crm_order.bill_no" // 单号排序
	case 3:
		field = "crm_order.bill_type" // 支付类型
	case 4:
		field = "crm_order.real_price" // 实付价格
	case 5:
		field = "crm_order.pay_type" // 支付方式
	}
	err = Db(2).Table(val.TName).
		Where(val.ToWhere()).
		Desc(field).
		Limit(val.Count, (val.Page-1)*val.Count).
		Find(&list)
	val.Total, _ = Db(2).Table(val.TName).
		Where(val.ToWhere()).
		Desc(field).
		Count(this)

	if err == nil {
		val.List = list
		for i, row := range list {
			list[i].Teacher = GetTeacher(row.Teac)
		}
	}
	return err
}
func (this *CrmOrder) CountOrder(where string) (int64, error) {
	total, err := Db(2).Table("crm_order").
		Where(where).
		Count(this)
	return total, err
}
